package netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.CharsetUtil;

/**
 * Netty客户端
 */
public class NettyClient {

    public static final int PORT = 9000;

    public static void main(String[] args) {
        //创建完成IO通信的线程组
        EventLoopGroup workGroup = new NioEventLoopGroup(2);
        try {
            //创建服务器启动对象
            Bootstrap bootstrap = new Bootstrap();
            //设置线程组
            bootstrap.group(workGroup)
                    //设置通道的类型
                    .channel(NioSocketChannel.class)
                    //设置通道的初始化器
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            //给通道中的管道加处理器
                            socketChannel.pipeline().addLast(new NettyClientHandler());
                        }
                    });
            //连接服务器端
            ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", PORT).sync();
            //关闭客户端
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //关闭线程组
            workGroup.shutdownGracefully();
        }
    }
}

/**
 * 客户端的输入处理器
 */
class NettyClientHandler extends ChannelInboundHandlerAdapter {

    /**
     * 连接服务器成功
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("连接服务器成功");
        //发送消息给服务器端
        ByteBuf byteBuf = Unpooled.copiedBuffer("Hello 服务器端，我是客户端".getBytes(CharsetUtil.UTF_8));
        ctx.writeAndFlush(byteBuf);
    }

    /**
     * 读取操作
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //获得客户端发送的数据
        ByteBuf byteBuf = (ByteBuf) msg;
        System.out.println("收到服务器端消息：" + byteBuf.toString(CharsetUtil.UTF_8));
    }

    /**
     * 异常处理
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //关闭通道
        ctx.close();
    }
}
